import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { useWebSocket } from '../hooks/useWebSocket'
import { useHeartbeat } from '../hooks/useHeartbeat'
import platformAPI from '../utils/platformAPI';
// 顶部添加导入
import { getClientType, generateClientId } from '../utils/platformDetector';

export const useAppStore = defineStore('app', () => {
  // 状态
  const alerts = ref([])
  const activeAlerts = ref([])
  const settings = ref({
    serverUrl: 'ws://localhost:8000/ws',
    alertSound: true,
    alertVibration: true,
    alertTimeRange: {
      start: '00:00',
      end: '23:59'
    },
    // 新增客户端参数
    clientName: 'My Device',
    clientId: null,
    clientType: getClientType()
  })

  const connectionStatus = ref('disconnected') // connected, disconnected, connecting


  // 初始化WebSocket和心跳
  const {connect, sendMessage, close } = useWebSocket(
    settings.value.serverUrl,
    handleWebSocketMessage,
    handleWebSocketOpen,
    handleWebSocketClose
  )

  const { startHeartbeat, stopHeartbeat, resetFailureCount } = useHeartbeat(
    () => sendMessage({ type: 'heartbeat', timestamp: Date.now() }),
    10000, // 30秒一次心跳
    3,     // 3次失败视为断线
    handleHeartbeatFailure
  )

  // WebSocket事件处理
  function handleWebSocketOpen() {
    connectionStatus.value = 'connected'
    startHeartbeat()
    // 连接成功后获取所有提醒
    sendMessage({ type: 'get_all_alerts' })
  }

  function handleWebSocketClose() {
    connectionStatus.value = 'disconnected'
    stopHeartbeat()
    // 尝试重连
    setTimeout(() => connect(getWebSocketUrl()), 5000)
  }

  function handleWebSocketMessage(event) {
    try {
      const message = JSON.parse(event.data)

      switch (message.type) {
        case 'alert':
          // 收到新提醒
          addAlert(message.data)
          break
        case 'alert_closed':
          // 提醒被关闭
          closeAlert(message.alertId)
          break
        case 'all_alerts':
          // 所有提醒列表
          message.data.forEach((alert) => {
            alerts.value.push(alert)
          });

          break
        case 'alert_added':
          // 新增提醒确认
          alerts.value.push(message.data)
          break
        case 'heartbeat_ack':
          // 处理心跳响应
          resetFailureCount()
          break
        default:
          console.log('未知消息类型:', message.type)
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error, event.data)
    }
  }

  // 心跳失败处理
  function handleHeartbeatFailure() {
    connectionStatus.value = 'disconnected'
    // 尝试重连
    close()
    setTimeout(() => connect(settings.value.serverUrl), 5000)
  }

  // 提醒相关方法
  function addAlert(alertData) {
    // 检查是否在提醒时间范围内
    const now = new Date()
    const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`
    const inTimeRange = isTimeInRange(currentTime, settings.value.alertTimeRange.start, settings.value.alertTimeRange.end)

    if (inTimeRange) {
      // 添加到活跃提醒
      activeAlerts.value.push(alertData)
      // 显示系统提醒 - 使用平台兼容API
      platformAPI.showAlert({
        title: alertData.title,
        message: alertData.content,
        id: alertData.id
      })
    }
  }

  function closeAlert(alertId) {
    // 从活跃提醒中移除
    activeAlerts.value = activeAlerts.value.filter(alert => alert.id !== alertId)
    // 通知服务器提醒已关闭
    sendMessage({
      type: 'close_alert',
      alertId: alertId
    })
    // 通知主进程关闭提醒窗口
    window.electronAPI.closeAlert(alertId)
  }

  function createNewAlert(alertData) {
    // 发送新提醒到服务器
    sendMessage({
      type: 'add_alert',
      data: alertData
    })
  }

  // 时间范围检查工具函数
  function isTimeInRange(time, start, end) {
    const timeToMinutes = (t) => {
      const [h, m] = t.split(':').map(Number)
      return h * 60 + m
    }

    const t = timeToMinutes(time)
    const s = timeToMinutes(start)
    const e = timeToMinutes(end)

    if (s <= e) {
      return t >= s && t <= e
    } else {
      return t >= s || t <= e
    }
  }


  // 从本地存储加载设置
  function loadSettings() {
    const saved = localStorage.getItem('appSettings')
    if (saved) {
      settings.value = JSON.parse(saved)
    }

    // 如果没有clientId，生成一个新的并保存
    if (settings.value.clientId == null) {
      settings.value.clientId = generateClientId();
      saveSettings(settings.value); // 保存新生成的clientId
    }

    // 确保clientType是最新的
    settings.value.clientType = getClientType();
  }

  // 初始化
  function init() {
    loadSettings()
    const svrUrl = getWebSocketUrl()
    connect(svrUrl)

    // 监听其他客户端关闭提醒的事件
    platformAPI.onAlertClosed((event, alertId) => {
      closeAlert(alertId)
    })
  }

  // 添加生成WebSocket URL的函数
  function getWebSocketUrl() {
    try {
      const url = new URL(settings.value.serverUrl);
      // 替换路径为新格式（保留协议、主机、端口）
      url.pathname = `/ws/${settings.value.clientId}/${encodeURIComponent(settings.value.clientName)}/${settings.value.clientType}`;
      return url.toString();
    } catch (e) {
      console.error('无效的服务器URL:', e);
      return settings.value.serverUrl; // 降级处理
    }
  }

// 修改saveSettings函数，当服务器地址或客户端参数变化时重新连接
  function saveSettings(newSettings) {
    const oldUrl = getWebSocketUrl();
    settings.value = { ...settings.value, ...newSettings };

    // 如果WebSocket URL变化，重新连接
    const newUrl = getWebSocketUrl();
    if (newUrl !== oldUrl) {
      close();
      connect(newUrl);
    }

    localStorage.setItem('appSettings', JSON.stringify(settings.value));
  }

  return {
    alerts,
    activeAlerts,
    settings,
    connectionStatus,
    init,
    closeAlert,
    createNewAlert,
    saveSettings
  }
})
